<template>
  <div class="upload-clothes-container">
    <!-- 返回图标 -->
    <div class="back-icon" @click="handleBack">
      <van-icon name="arrow-left" size="24" color="#333" />
    </div>

    <!-- 图片上传与展示区域 -->
    <div class="image-upload-section">
      <!-- 隐藏的文件输入框 -->
      <input
        type="file"
        ref="fileInput"
        accept="image/*"
        @change="handleFileChange"
        style="display: none"
      />

      <div v-if="!uploadedImage" class="upload-placeholder">
        <van-icon name="camera-o" size="60" color="#ccc" />
        <p>点击上传衣物照片</p>
        <van-button
          type="primary"
          color="#000000"
          size="small"
          @click="$refs.fileInput.click()"
        >
          选择图片
        </van-button>
      </div>

      <div v-else class="image-preview">
        <img :src="uploadedImage" alt="衣物预览" class="preview-image" />
        <div class="image-actions">
          <van-icon
            name="edit"
            size="24"
            color="#000000"
            @click="$refs.fileInput.click()"
            class="edit-icon"
          />
        </div>
      </div>
    </div>

    <!-- 分类选择器 -->
    <!-- <div v-if="uploadedImage" class="category-selector-section">
      <ClothesCategoryPicker
        v-model="selectedCategory"
        @change="handleCategoryChange"
      />
    </div> -->
    <div class="form-group" v-if="uploadedImage">
      <van-field
        input-align="right"
        is-link
        readonly
        label="分类"
        :placeholder="clothesType[1].text"
        @click="showCategoryPopup = true"
        style="padding: 0"
      />
    </div>

    <!-- 底部上传按钮 -->
    <div v-if="uploadedImage" class="bottom-actions">
      <button
        type="primary"
        size="large"
        @click="handleUpload"
        :loading="isUploading"
      >
        {{ isUploading ? "上传中..." : "开始上传" }}
      </button>
    </div>

    <!-- 处理中提示 -->
    <van-overlay v-if="isProcessing" :show="true" class="processing-overlay">
      <div class="processing-content">
        <van-loading type="spinner" size="48" color="#6c63ff" />
      </div>
    </van-overlay>

    <!-- 分类选择弹窗 -->
    <van-popup v-model:show="showCategoryPopup" position="bottom" :round="true">
      <van-picker
        title="选择衣物分类"
        :columns="clothesCategories"
        confirm-button-text=""
        cancel-button-text=""
        v-model="selectedCategoryIndexes"
      >
        <template #columns-bottom>
          <div class="picker-bottom">
            <div class="popup-actions">
              <div class="cancel-btn" @click="showCategoryPopup = false">
                取消
              </div>
              <div class="confirm-btn" @click="onCategoryConfirm">确认</div>
            </div>
          </div>
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import { useClothesStore } from "../store/clothes";
import ClothesCategoryPicker from "../components/ClothesCategoryPicker.vue";
import { formatDate } from "../utils/formatDate";
import { clothesCategories } from "../utils/clothesCategory";

const router = useRouter();
const clothesStore = useClothesStore();

// 响应式变量
const uploadedImage = ref("");
const selectedCategory = ref(null);
const isProcessing = ref(false);
const isUploading = ref(false);
const showCategoryPopup = ref(false);

const clothesType = ref([{ text: "" }, { text: "" }]);
// 选中的分类索引
const selectedCategoryIndexes = ref([]);

// 处理分类选择变化
const handleCategoryChange = (category) => {
  // 这里可以添加任何需要在分类改变时执行的逻辑
  console.log("分类已选择:", category);
  // 例如：可以根据选择的分类预填一些相关信息
  // 或者触发一些相关的业务逻辑
};
// 分类选择确认 - 使用v-model绑定的值
const onCategoryConfirm = () => {
  if (
    Array.isArray(selectedCategoryIndexes.value) &&
    selectedCategoryIndexes.value.length > 0
  ) {
    const firstLevelValue = selectedCategoryIndexes.value[0];
    const secondLevelValue = selectedCategoryIndexes.value[1];

    try {
      // Find first level category by value
      const firstLevelCategory = clothesCategories.find(
        (cat) => cat.value === firstLevelValue
      );

      if (firstLevelCategory) {
        // If second level value is provided, find and add it
        if (secondLevelValue && firstLevelCategory.children) {
          const secondLevelCategory = firstLevelCategory.children.find(
            (child) => child.value === secondLevelValue
          );
          if (secondLevelCategory) {
            clothesType.value = [
              { ...firstLevelCategory, children: undefined },
              { ...secondLevelCategory },
            ];
          }
        }
      }
    } catch (error) {
      console.error("Error finding category text by value:", error);
    }
  }
  showCategoryPopup.value = false;
};
// 处理返回
const handleBack = () => {
  router.back();
};

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型（JPG/PNG/WebP）
    const allowedTypes = ["image/jpeg", "image/png", "image/webp"];
    if (!allowedTypes.includes(file.type)) {
      showToast({
        message: "请上传JPG/PNG/WebP格式的图片",
        position: "bottom",
        duration: 3000,
      });
      return;
    }
    // 检查文件大小（限制5MB）
    if (file.size > 5 * 1024 * 1024) {
      showToast({
        message: "文件大小不能超过5MB",
        position: "bottom",
        duration: 3000,
      });
      return;
    }

    isProcessing.value = true;

    try {
      // 调用图片处理接口移除背景
      const processedImageData = await removeBg(file);
      // 将处理后的图片转为DataURL
      const blob = new Blob([processedImageData], { type: "image/png" });
      const reader = new FileReader();
      reader.onload = (e) => {
        uploadedImage.value = e.target.result;
        isProcessing.value = false;
        showToast("图片处理完成");
      };
      reader.onerror = () => {
        console.error("FileReader读取失败");
        isProcessing.value = false;
        showToast("图片处理失败，请稍后重试");
      };
      reader.readAsDataURL(blob);
    } catch (error) {
      console.error("图片处理失败:", error);
      isProcessing.value = false;
      showToast("图片处理失败，请稍后重试");

      // 即使处理失败，也显示原图作为备用
      const reader = new FileReader();
      reader.onload = (e) => {
        uploadedImage.value = e.target.result;
      };
      reader.onerror = () => {
        console.error("FileReader读取原图失败");
        uploadedImage.value = "";
      };
      reader.readAsDataURL(file);
    } finally {
      // 移除finally块中的isProcessing设置，避免与异步回调冲突
    }
  }
};

// 移除背景图片处理函数
const removeBg = async (file) => {
  const formData = new FormData();
  formData.append("size", "auto");
  formData.append("image_file", file);

  try {
    const response = await fetch("https://api.remove.bg/v1.0/removebg", {
      method: "POST",
      headers: {
        "X-Api-Key": "LKUL75eu2ty27UHDFNkErBiA",
      },
      body: formData,
    });

    if (response.ok) {
      return await response.arrayBuffer();
    } else {
      throw new Error(`${response.status}: ${response.statusText}`);
    }
  } catch (error) {
    console.error("调用remove.bg接口失败:", error);
    throw error;
  }
};

// 上传衣物
const handleUpload = async () => {
  if (!uploadedImage.value || !clothesType.value[0].text) {
    showToast("请上传图片并选择分类");
    return;
  }

  isUploading.value = true;

  try {
    // 构建上传数据 - 只包含必需的字段：图片和分类
    // 其他相关数据（如颜色、品牌等）将在后续的编辑流程中由用户补充
    const clothesData = {
      type: clothesType.value, // 必需：分类数据
      imageUrls: [uploadedImage.value], // 必需：图片数据
      purchaseDate: formatDate(new Date()),
    };

    // 调用添加衣物的API
    const newClothes = await clothesStore.addClothes(clothesData);

    showToast("上传成功");

    // 上传成功后跳转到衣物详情页，可以让用户补充其他信息
    router.push(`/clothes`);
  } catch (error) {
    console.error("上传失败:", error);
    showToast((error && error.message) || "上传失败，请稍后重试");
  } finally {
    isUploading.value = false;
  }
};
</script>

<style scoped>
.upload-clothes-container {
  padding: 20px;
  /* min-height: 100vh; */
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.back-icon {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
  padding: 10px;
}

.image-upload-section {
  margin-top: 60px;
  margin-bottom: 80px;
  width: 100%;
  display: flex;
  justify-content: center;
}

.upload-placeholder {
  width: 200px;
  height: 200px;
  border: 2px dashed #ccc;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.upload-placeholder p {
  margin: 10px 0;
  color: #999;
}

.image-preview {
  position: relative;
  width: 250px;
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  overflow: hidden;
  /* background-color: #f5f5f5; */
}

.preview-image {
  max-width: 230px;
  max-height: 230px;
  transition: transform 0.3s ease;
}

.image-actions {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.edit-icon {
  background-color: rgba(255, 255, 255, 0.8);
  padding: 5px;
  border-radius: 50%;
}

.rotate-control {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 10px 20px;
  border: 1px solid #eee;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.rotate-control:hover {
  background-color: #f8f8f8;
}

.rotate-control span {
  margin-left: 8px;
  color: #409eff;
}

.category-selector-section {
  width: 100%;
  margin-bottom: 40px;
}

.bottom-actions {
  width: 100%;
  display: flex;
  justify-content: center;
}
.bottom-actions button {
  width: 100%;
  padding: 13px 0;
  background-color: #000000;
  color: #fff;
  border-radius: 12px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 30px;
}

.processing-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
}

.processing-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.processing-content p {
  margin-top: 15px;
  color: #666;
}
.form-group {
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  width: 100%;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}
.picker-bottom {
  padding: 15px 0 35px 0;
  width: 60%;
  margin: 0 auto;
}
.popup-actions {
  background-color: #f0f0f0;
  border-radius: 8px;
  display: flex;
  justify-content: center;
}

.cancel-btn,
.confirm-btn {
  width: 50%;
  border-radius: 8px;
  transition: all 0.3s ease;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  color: #000000;
}

.confirm-btn {
  background-color: #000000;
  color: #f0f0f0;
}
</style>
